package cn.stylefeng.guns.sys.modular.system.controller;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.listener.MtsxfExcelListener;
import cn.stylefeng.guns.sys.core.listener.TpfkExcelListener;
import cn.stylefeng.guns.sys.core.util.JsonResult;
import cn.stylefeng.guns.sys.modular.system.ApiEntity.Ksda;
import cn.stylefeng.guns.sys.modular.system.ApiEntity.Yfd;
import cn.stylefeng.guns.sys.modular.system.entity.BtyMtsxf;
import cn.stylefeng.guns.sys.modular.system.entity.BtyTpfk;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyTpfkMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyMtsxfParam;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyTpfkParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyMtsxfResult;
import cn.stylefeng.guns.sys.modular.system.service.BtyTpfkService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;


/**
 * 控制器
 *
 * @author liuy
 * @Date 2022-01-10 14:46:57
 */
@Controller
@RequestMapping("/btyTpfk")
public class BtyTpfkController extends BaseController {

    private String PREFIX = "/modular/system/btyTpfk";

    @Resource
    private BtyTpfkService btyTpfkService;
    @Resource
    private BtyTpfkMapper tpfkMapper;

    /**
     * 跳转到主页面
     *
     * @author liuy
     * @Date 2022-01-10
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/btyTpfk.html";
    }

    /**
     * 新增页面
     *
     * @author liuy
     * @Date 2022-01-10
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/btyTpfk_add.html";
    }

    /**
     * 编辑页面
     *
     * @author liuy
     * @Date 2022-01-10
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/btyTpfk_edit.html";
    }

    /**
     * 新增接口
     *
     * @author liuy
     * @Date 2022-01-10
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(BtyTpfkParam btyTpfkParam) {
        this.btyTpfkService.add(btyTpfkParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author liuy
     * @Date 2022-01-10
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(BtyTpfkParam btyTpfkParam) {
        this.btyTpfkService.update(btyTpfkParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author liuy
     * @Date 2022-01-10
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(BtyTpfkParam btyTpfkParam) {
        this.btyTpfkService.delete(btyTpfkParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author liuy
     * @Date 2022-01-10
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(BtyTpfkParam btyTpfkParam) {
        BtyTpfk detail = this.btyTpfkService.getById(btyTpfkParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author liuy
     * @Date 2022-01-10
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(BtyTpfkParam btyTpfkParam) {
        return this.btyTpfkService.findPageBySpec(btyTpfkParam);
    }

    /**
     * 导入excel
     */
    @RequestMapping("/import")
    @ResponseBody
    public Object addUsers(@RequestParam("file") MultipartFile file, BtyMtsxfParam mtsxfParam) {
        JsonResult jsonResult = new JsonResult();
        if(ToolUtil.isEmpty(mtsxfParam.getZdrq())){
            jsonResult.setState(0);
            jsonResult.setErrmsg("请先选择制单日期！");
            return jsonResult;
        }
        //导入之前删掉之前的数据
        tpfkMapper.delete(new QueryWrapper<>());
        try {
            TpfkExcelListener basicExcelListener = new TpfkExcelListener(btyTpfkService);
            //EasyExcel.read(file.getInputStream(), BtyTpfk.class, basicExcelListener).sheet(0).headRowNumber(2).doRead();
            EasyExcel.read(file.getInputStream(), BtyTpfk.class, basicExcelListener).sheet(0).doRead();
            //导入成功之后按大区生成凭证
            String zdrq=mtsxfParam.getZdrq();
            String bh = "201";
            String   zy = "退货单";
            List<BtyTpfk>list=btyTpfkService.list();
            for (BtyTpfk btyTpfk : list) {
                BigDecimal je = btyTpfk.getJe();
                String ksbm = "";
                String dm = btyTpfk.getDm();

                //根据店名查询客商辅助核算编码
                String json = "{\"custname\":\"" + dm + "\"}";
                RestTemplate restTemplate = new RestTemplate();
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                headers.add("trantype", "code"); // 档案翻译方式，枚举值为：编码请录入 code， 名称请录入 name， 主键请录入 pk
                headers.add("system", "001"); // 系统编码
                headers.add("usercode", "15253172037"); // 用户
                headers.add("password", "514576f58a89767b46c1b44767a08f77");
                headers.add("Accept", MediaType.APPLICATION_JSON.toString());

                HttpEntity<String> formEntitys = new HttpEntity<String>(json, headers);
                String urls = "http://124.70.28.147:8089/u8cloud/api/uapbd/custdoc/query";

                Yfd yfd = restTemplate.postForEntity(urls, formEntitys, Yfd.class).getBody();
                JSONObject resultObject = JSON.parseObject(yfd.getData());
                JSONArray jsonArray = resultObject.getJSONArray("datas");
                JSONObject jsonObject;
                if (jsonArray != null) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        jsonObject = jsonArray.getJSONObject(0);
                        Ksda.DatasBean.ParentvoBean parentvo = jsonObject.getObject("parentvo", Ksda.DatasBean.ParentvoBean.class);
                        ksbm = parentvo.getCustcode();
                    }
                }
                if(dm.equals("东营广饶博兴啤酒直通")){
                    ksbm="020600014";
                }else if(dm.equals("博兴啤酒直通")){
                    ksbm="020600130";
                }

                StringBuilder sb = new StringBuilder();
                sb.append("{\n" +
                        "    \"voucher\":[\n" +
                        "        {\n" +
                        "            \"details\":[");
                sb.append(
                        "{\n" +
                                "\t\t\t\t\"ass\":[\n" +
                                "                        {\n" +
                                "                            \"checktypecode\":\"73\",\n" +
                                "                            \"checkvaluecode\":'" + ksbm + "'\n" +//客商辅助核算编码
                                "                        },\n" +
                                "                    ],\n" +
                                "                    \"creditamount\":\"\",\n" +
                                "                    \"creditquantity\":\"\",\n" +
                                "                    \"debitamount\":\"" + je + "\",\n" +//借方金额
                                "                    \"debitquantity\":\"\",\n" +
                                "                    \"detailindex\":\"\",\n" +
                                "                    \"excrate1\":\"\",\n" +
                                "                    \"explanation\":\"" + zy + "\",\n" +//借方摘要
                                "                    \"localcreditamount\":\"\",\n" +
                                "                    \"localdebitamount\":\"\",\n" +
                                "                    \"pk_accsubj\":\"1122\",\n" +//借方科目编码
                                "                    \"pk_currtype\":\"CNY\",\n" +
                                "                    \"price\":\"\"\n" +
                                "                },\n" +
                                "                {\n" +
                                "                    \"creditamount\":\"" + je + "\",\n" +//贷方金额
                                "                    \"debitamount\":\"\",\n" +
                                "                    \"explanation\":\"" + zy + "\",\n" +//贷方摘要
                                "                    \"localcreditamount\":\"\",\n" +
                                "                    \"localdebitamount\":\"\",\n" +
                                "                    \"pk_accsubj\":\"6001\",\n" +//贷方科目编码
                                "                    \"pk_currtype\":\"CNY\"\n" +
                                "                },");
                sb.append("            ],\n" +
                        "            \"pk_corp\":" + bh + ",\n" +
                        "            \"pk_glorgbook\":\"" + bh + "-bty01\",\n" +
                        "            \"pk_prepared\":\"15253172037\",\n" +
                        "            \"pk_vouchertype\":\"记账\",\n" +
                        "            \"prepareddate\":\"" + zdrq + "\"\n" +
                        "        }\n" +
                        "    ]\n" +
                        "}");

                System.out.println("sb:"+sb.toString());
                HttpEntity<String> formEntity = new HttpEntity<String>(sb.toString(), headers);
                String url = "http://124.70.28.147:8089/u8cloud/api/gl/voucher/insert";
                String result = restTemplate.postForEntity(url, formEntity, String.class).getBody();
                //System.out.println("result:"+result);
                JsonParser jp = new JsonParser();
                //将json字符串转化成json对象
                JsonObject jo = jp.parse(result).getAsJsonObject();
                //获取status对应的值
                String status = jo.get("status").getAsString();

                if (status.equals("falied")) {
                    String errormsg = jo.get("errormsg").getAsString();
                    //System.out.println("errormsg:" + errormsg);
                    BtyTpfk tpfk=btyTpfkService.getOne(new QueryWrapper<BtyTpfk>().eq("dm",dm));
                    if(ToolUtil.isNotEmpty(tpfk)){
                        tpfk.setErrormsg(errormsg);
                        btyTpfkService.updateById(tpfk);
                    }
                }else{
                    BtyTpfk tpfk=btyTpfkService.getOne(new QueryWrapper<BtyTpfk>().eq("dm",dm));
                    if(ToolUtil.isNotEmpty(tpfk)){
                        tpfk.setFlag(1);
                        btyTpfkService.updateById(tpfk);
                    }
                }
            }

        }catch (Exception e) {
            e.printStackTrace();
            jsonResult.setState(0);
            jsonResult.setErrmsg(e.getMessage());
            return jsonResult;
        }
        return true;
    }

}


